import { defineStore } from "pinia";
import { store } from "../index";
import { getStorage, setStorage } from "../../utils/tools";
import * as cityApi from "../../api/city";

export const useLocationStore = defineStore("location", {
  state: () => ({
    allCitydata: [],
    hotCityData: [],
    latitude: getStorage("location_latitude") || null,
    longitude: getStorage("location_longitude") || null,
    currentCityinfo: getStorage("location_currentCityinfo") || null,
    selectCityinfo: getStorage("location_selectCityinfo") || null,
  }),
  getters: {
    getSelectCityinfo() {
      if (this.selectCityinfo) {
        return this.selectCityinfo;
      } else {
        return this.currentCityinfo;
      }
    },
  },
  actions: {
    async getAllCitydata() {
      const res: any = await cityApi.all();
      this.setAllCitydata(res);
      const hotCityData = res.filter((item) => {
        return item.ishot === 1;
      });
      this.setHotCityData(hotCityData);
    },
    setAllCitydata(data){
      this.allCitydata = data;
    },
    setHotCityData(arr) {
      this.hotCityData = arr.slice(0,3);
    },
    setLocation(latitude, longitude, city) {
      if(!(this.allCitydata.length > 0)) {
        return
      }
      this.latitude = latitude;
      this.longitude = longitude;
      this.currentCityinfo = this.allCitydata.find((item) => {
        return city.includes(item.cityName);
      });
      if (!this.selectCityinfo){
        this.setSelectCityinfo(this.currentCityinfo);
      } 
      setStorage("location_latitude", this.latitude);
      setStorage("location_longitude", this.longitude);
      setStorage("location_currentCityinfo", this.currentCityinfo);
    },
    setSelectCityinfo(data) {
      this.selectCityinfo = data;
      setStorage("location_selectCityinfo", this.selectCityinfo);
    },
  },
});

export function getLocationStore() {
  return useLocationStore(store);
}
